package com.ivy.controller.AiClient.service.impl;

import com.alibaba.fastjson.JSON;
import com.ivy.controller.AiClient.bean.ChatCompletionResponse;
import com.ivy.controller.AiClient.bean.ChatConfig;
import com.ivy.controller.AiClient.service.IAiClientService;
import jakarta.annotation.Resource;
import okhttp3.*;
import okio.Buffer;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: liuYifan
 * @CreateTime: 2025-02-24  09:23
 * @Description: TODO
 */

@Service
public class AiClientServiceImpl implements IAiClientService {
    //引入这个bean
    @Resource
    private ChatConfig config;

    @Override
    public ChatCompletionResponse generateStreamAsString(String message) {
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, "{\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"content\": \"" + "请介绍一下你自己" + "\",\n" +  // 动态插入用户消息
                "      \"role\": \"user\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"content\": \"" + message + "\",\n" +  // 动态插入用户消息
                "      \"role\": \"user\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"model\": \"deepseek-chat\",\n" +
                "  \"frequency_penalty\": 0,\n" +
                "  \"max_tokens\": 1024,\n" +
                "  \"presence_penalty\": 0,\n" +
                "  \"response_format\": {\n" +
                "    \"type\": \"text\"\n" +
                "  },\n" +
                "  \"stop\": null,\n" +
                "  \"stream\": false,\n" +
                "  \"stream_options\": null,\n" +
                "  \"temperature\": 1,\n" +
                "  \"top_p\": 1,\n" +
                "  \"tools\": null,\n" +
                "  \"tool_choice\": \"none\",\n" +
                "  \"logprobs\": false,\n" +
                "  \"top_logprobs\": null\n" +
                "}");
        Buffer buffer = new Buffer();
        try {
            requestBody.writeTo(buffer);
            System.out.println("Request Body Content: " + buffer.readUtf8());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建 Headers
        Headers headers = new Headers.Builder()
                .add("Content-Type", "application/json")
                .add("Accept", "application/json")
                .add("Authorization", "Bearer " + config.getDeepSeekConfigKey())  // 使用您的 API 密钥
                .build();
        // 创建 HttpUrl
        HttpUrl url = HttpUrl.parse(config.getDeepSeekConfigUrl());
        if (url == null) {
            throw new IllegalArgumentException("您此时未携带URL参数");
        }
        // 构造 Request
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(headers)
                .build();
        // 执行请求并打印响应
        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            System.out.println(responseBody);
            ChatCompletionResponse responseVo = JSON.parseObject(responseBody, ChatCompletionResponse.class);
            return responseVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
